const { reject } = require("lodash")

// promise 就是一个类，在执行类的时候需要传递一个执行器executor进去，执行器会立即执行
const PENDING = 'pending'  // 等待
const FULFILED = 'fulfiled'
const REGECTED = 'rejected'
class MyPromise {
    constructor(executor){
        try {
            executor(this.resolve, this.reject)
        } catch(e) {
            this.reject(e)
        }
    }
    reason = undefined
    value = undefined
    // 异步时保存回调函数
    failCallback = []
    successCallback = []
    status = PENDING
    resolve= (value)=>{
        // 如果状态不是等待，阻止执行
        if(this.status !=PENDING) return
        // 将状态改为成功
        this.status=FULFILED
        // 保存成功后的值
        this.value = value
        // 异步执行后，立即执行回调函数
        // this.successCallback(value)
        while (this.successCallback.length) this.successCallback.shift()(this.value)
    }
    reject=(reason)=>{
        if(this.status !=PENDING) return
        this.status=REGECTED
        this.reason = reason
        while (this.failCallback.length) this.failCallback.shift()(this.reason)
        // this.failCallback(reason)
    }
    then(successCallback,failCallback){
        // 没有传参数时的直接传递
        successCallback = successCallback? successCallback: value => value
        failCallback = failCallback? failCallback: reason => {throw reason}
        let promise2 = new MyPromise((resolve, reject)=>{
            if(this.status === FULFILED){
                // 采用setTimeOut是为了将代码编程异步，而不是延迟，故时间为0
                setTimeout(()=>{
                    try {
                        // 同步直接调用
                        let x = successCallback(this.value)
                        // resolve(x)
                        // 在promise2执行的过程中无法获取到promise2,将代码变成异步就可以解决
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                    
                }, 0)
            } else if (this.status === REGECTED){
                setTimeout(()=>{
                    try {
                        // 同步直接调用
                        let x = failCallback(this.reason)
                        // resolve(x)
                        // 在promise2执行的过程中无法获取到promise2,将代码变成异步就可以解决
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                    
                }, 0)
            } else {
                // 异步处理，状态为等待时保存回调函数
                this.successCallback.push(()=>{
                    setTimeout(()=>{
                        try {
                            // 同步直接调用
                            let x = successCallback(this.value)
                            // resolve(x)
                            // 在promise2执行的过程中无法获取到promise2,将代码变成异步就可以解决
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                        
                    }, 0)
                })
                this.failCallback.push(()=>{
                    setTimeout(()=>{
                        try {
                            // 同步直接调用
                            let x = failCallback(this.reason)
                            // resolve(x)
                            // 在promise2执行的过程中无法获取到promise2,将代码变成异步就可以解决
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                        
                    }, 0)
                })
            }
        })
        return promise2
    }
    finally(callback){
        return this.then((value)=>{
            return MyPromise.resolve(callback()).then(()=>value)
            // callback()
            // return value
        },(reason)=>{
            return MyPromise.resolve(callback()).then(()=>{throw reason})
            // callback()
            // throw reason
        })
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    static all(array){
        let result = []
        let index = 0
        return new MyPromise((resolve,reject)=>{
            function addDate(key,value) {
                result[key] = value
                index++  
                if(index === array.length){
                    resolve(result)
                }      
            }
            array.forEach((item, index) => {
                if (item instanceof MyPromise) {
                    item.then(value => addDate(index, value), reason=>reject(reason))
                } else {
                    // 普通值
                    addDate(index,item)
                }
            });
        })
    }
    static resolve(value){
        if(value instanceof MyPromise) return value;
        return new MyPromise((resolve=>resolve(value)))
    }
}

function resolvePromise (promise2, x, resolve, reject){
    // 如果返回自己的promise对象
    if(promise2 === x){
        return reject(new TypeError('Chaining cycle detexted for promise #<promise>'))
    }
    // 判断是否返回promise对象
    if(x instanceof MyPromise){
        x.then(resolve,reject)
    } else {
        resolve(x)
    }
}

module.exports = MyPromise
